var express = require('express');
var router = express.Router();

const Query = require('../utils/db.js')

//引入包md5和uuid
const md5 = require('md5')
const { v4: uuidv4 } = require('uuid');

//引入md5锁子、生成token的方法
const {md5Screat,getToken} = require('../utils/config.js')


/* GET home page. */
router.get('/', async function (req, res, next) {
    res.send('登录注册业务')
});

//注册
router.post('/register', async function (req, res, next) {
    //1. 接收参数
    let { username = '', password = '', repwd = '' } = req.body
    // console.log( username,password,repwd );

    // res.send('ok123')
    // return
    //2. 业务判断
    //2.1 不为空
    if (username == '' || password == '' || repwd == '') {
        next({
            "msg": "请传递必要参数",
            "status": 500
        })
        return
    }
    //2.2 两次密码保持一致
    if (password != repwd) {
        next({
            "msg": "两次密码不一致",
            "status": 500
        })
        return
    }


    //3. 书写sql语句

    //先判断用户名是否注册
    let sql2 = `
            SELECT * FROM e_member WHERE username = '${username}'
        `
    let res2 = await Query(sql2)
    if (res2.result.length > 0) {
        next({
            "msg": "用户已被注册了",
            "status": 500
        })
        return
    }

    //mid用以前的 uuid
    //createdate = Date.now()
    //密码：请用md5模块 https://www.npmjs.com/package/md5
    password = md5(password + md5Screat)
    let createdate = Date.now()
    let mid = uuidv4()
    let sql1 = `INSERT INTO e_member (  mid,username,password,createdate) VALUES ( '${mid}','${username}','${password}','${createdate}' )`

    //4. 执行ssql
    let res1 = await Query(sql1)
    if (res1.result.affectedRows > 0) {
        let data = {
            "msg": "OK",
            "status": 200
        }
        res.send(data)
    }
});

//登录
router.post('/login', async function (req, res, next) {
    //1 . 接收参数
    let { username = '', password = '' } = req.body
    //2. 业务判断
    //2.1 不为空
    if (username == '' || password == '') {
        next({
            "msg": "请传递必要参数",
            "status": 500
        })
        return
    }

    password = md5(password + md5Screat) //同样的md5加密，然后拼接sql语句
    let sql = `SELECT * FROM e_member WHERE username = '${username}' AND password = '${password}'`

    // console.log( sql );

    let res1 = await Query(sql)
    
    if (res1.result.length > 0) {
        let mid = res1.result[0].mid
        let username = res1.result[0].username
        let data = {
            username, //依据用户名和mid得到一个token（一般用mid生成token）
            mid
        }
        let token = getToken( data )
        //res.send( token )
        //return
        res.send({
            "msg": "登录成功",
            "status": 500,
            result:{ //返回登录成功的标识，代表你当前登录这个用户  
                token,
                mid
            }
        })
        return
    }else{
        next({
            "msg": "用户名或密码错误",
            "status": 500
        })
        return
    }
});

module.exports = router;
